<template>
	<view class="product">
		<view class="top">
			<view class="position-fixed" style="width: 100%;padding: 0 16px;box-sizing: border-box;">
				<view class="heavy-title fb">
					{{$t('product.text19')}}
				</view>
				<view class="product-search">
					<uni-easyinput class="uni-mt-5 u-input" placeholderStyle="font-size:15px;" :styles="{'font-size':'15px'}" style="border-radius: 26px!important;font-size: 15px;background-color: #f6f7fb;" :inputBorder="false" suffixIcon="search" v-model="keyWord" :placeholder="$t('product.text18')" @iconClick="iconClick"></uni-easyinput>
				</view>
				<view style="width: 100%;">
					<div class="tab-container fs14">
					  <view class="tab-container fs14">
					    <view v-for="(item, index) in classifyList" :key="index" :class="['tab',activeTabIndex==index?'active':'']" @click="switchTab(index)">
					      {{item.name}}
					    </view>
					    <view class="underline" :style="{transform: `translate(${(activeTabIndex*65)+24}px)`}"></view>
					  </view>
					</div>
				</view>
			</view>
		</view>
		<view class="p-lr-16" style="width: 100%;box-sizing: border-box;overflow-y: auto;height: calc(-225px + 100vh); padding-bottom: 10px;">
			<view class="content mt15" v-for="(item,index) in productsList" :key="index" @click="goDetails(item)">
				<view class="flex flex-1">
					<view class="name flex-1" style="width: 100px;">
						<view class="">{{item.name}}</view>
						<view class="flex mt5 text-des-color fs12">
							<text>{{$t('product.text1')}}</text>
							<text style="margin-left: 5px;">{{formatAmount(item.data.amount)}}</text>
						</view>
					</view>
					<view class="price fs12" style="max-width: 70px; overflow-wrap: break-word;">
						{{item.data.price}}
					</view>
					<view class="flex" style="width: 74px;justify-content: end;">
						<text :class="parseFloat(item.data.zf_rate)>0?'text-down':'text-up'">{{item.data.zf_rate}}%</text>
					</view>
				</view>
			</view>
			<uni-load-more :status="loadStatus" :contentText="contentText" @clickLoadMore="loadMore"></uni-load-more>
		</view>
	</view>
</template>

<script setup>
	import { onMounted, ref, watch } from 'vue';
	import { onReachBottom, onPageScroll,onShow, onHide } from '@dcloudio/uni-app'
	import { getLang, formatAmount } from '../utils/utils.js'
	import { getClassifyList, getProductsList } from '../api/index.js'
	import config from '../config';
	import useGlobalProperties from '../utils/useGlobalProperties.js'
	import WebSocketManager from '../utils/websocket.js';
	const { $t,$i18n } = useGlobalProperties()
	const classifyList = ref([])
	const loading = ref(false)
	const finished = ref(false)
	const keyWord = ref('')
	const activeTabIndex = ref(0)
	const pageCof = ref({
		page:1,
		size:10
	})
	const loadStatus = ref('loading')
	const contentText = {
		contentdown: $t('loadMore'),
		contentrefresh: $t('loading'),
		contentnomore: $t('noMore')
	}
	const productsList = ref([])
	const wsManager = ref(null)
	const loadMore = () =>{
		if(wsManager.value){
			stopWebSocket();
		}
		loading.value = true
		getProductsList({
			name:keyWord.value,
			products_classify_id:classifyList.value[activeTabIndex.value].id,
			...pageCof.value
		}).then(res =>{
			// console.log('产品列表', res.data);
			if (res.data.length < pageCof.value.size) {
				finished.value = true; // 如果数据不足一页，标记为已加载完
				loadStatus.value = 'noMore'
			}
			loadStatus.value = res.data.length==10?'more':'noMore'
			productsList.value = productsList.value.concat(res.data)
			const params = []
			productsList.value.forEach((item,index)=>{
				params.push(`market.${item.code}.ticker`)
			})
			// startWebSocket(params);
			pageCof.value.page++;
			loading.value = false
		})
	}
	const switchTab = (index) =>{
		activeTabIndex.value = index
		productsList.value = []
		pageCof.value.page = 1
		loadStatus.value = 'loading'
		finished.value = false
		loadMore();
	}
	onMounted(()=>{
		getClassifyList().then(res =>{
			// console.log('产品分类',res.data);
			classifyList.value = res.data
			classifyList.value.sort((a, b) => a.sort - b.sort);
			loadMore();
		})
	})
	// WebSocket 获取行情
	const startWebSocket  = (params) => {
		wsManager.value = new WebSocketManager('wss://api.huobi.pro/ws');
		wsManager.value.connect(params);
		// 设置消息回调
		wsManager.value.onMessage((data) => {
			// console.log('Received WebSocket data:', data);
			if(data && data.ch){
				productsList.value.forEach(item =>{
					if(data.ch.includes(item.code)){
						item.data.price = data.tick.close
						item.data.amount = data.tick.amount
						item.data.zf_rate = ((data.tick.lastPrice - data.tick.open)/data.tick.open*100).toFixed(2)
					}
				})
			}
		});
	}
	onShow(()=>{
		console.log('onshow');
		if(productsList.value.length>0 && !wsManager.value){
			// startWebSocket()
		}
	})
	onHide(()=>{
		console.log('onHide');
		// stopWebSocket()
	})
	const stopWebSocket = () => {
		if (wsManager.value) {
			wsManager.value.close();
		}
	}
	onReachBottom(()=>{
		// console.log("触底了");
		if (finished.value || loading.value) return; // 如果已加载完或正在加载，则不执行
		loadMore();
	})
	// 去往产品详情页
	const goDetails = (item) =>{
		uni.navigateTo({
			url:'/pages/product/product?id='+item.id+'&symbol='+item.code,
		})
	}
	// 顶部搜索
	const iconClick = () =>{
		productsList.value = []
		pageCof.value.page = 1
		loadMore();
	}
</script>

<style scoped lang="scss">
	.product{
		width: 100%;
		// min-height: 100vh;
		box-sizing: border-box;
		// padding: 0 16px;
		display: flex;
		flex-direction: column;
		color: #222;
		font-size: 14px;
	}
	.top {
	    height: calc(50px + 44px + 0px + 16px + 40px);
	    z-index: 1020;
	}
	.product-search{
	    padding: 10px 0;
	}
	.is-input-border {
	    border-radius: 26px !important;
	}
	.act_border{
		border: 1px solid #1a7acb;
	}
	.tab-container {
	  display: flex;
	  position: relative;
	}
	
	.tab {
	  padding: 5px 10px;
	  color: #666; /* 默认文字颜色 */
	  transition: color 0.3s; /* 切换文字颜色的动画 */
	}
	
	.tab.active {
	  color: #000; /* 激活状态文字颜色 */
	  font-weight: bold;
	}
	
	.underline {
	  position: absolute;
	  bottom: 0;
	  height: 4px;
	  width: 14px; /* 初始宽度 */
	  background: #3c9cff; /* 下划线颜色 */
	  transition-duration:300ms;
	  border-radius: 2px;
	}
	.content {
		width: 100%;
	}
	.overflow-hidden {
	    overflow: hidden;
	}
	.heavy-title {
	    padding-left: 20px;
	    font-size: 28px;
	    font-family: PingFang SC-Heavy,PingFang SC;
	}
</style>
